package com.itheima.Service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.UserMapper;
import com.itheima.Service.UserService;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.User;
import com.itheima.pojo.UserQueryVO;
import com.itheima.pojo.UserResultVO;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserResultVO> listUsers(UserQueryVO queryVO) {
        PageHelper.startPage(queryVO.getPage(), queryVO.getPageSize());
        return userMapper.selectUserList(queryVO);
    }

    @Override
    public int countUsers(UserQueryVO queryVO) {
        return userMapper.countUserList(queryVO);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

    @Override
    @Transactional
    public boolean addUser(User user) {
        // 设置默认值
        user.setStatus(1); // 默认为活跃状态
        user.setRole("user"); // 默认为普通用户
        user.setCreateTime(java.time.LocalDateTime.now());
        user.setUpdateTime(java.time.LocalDateTime.now());

        int result = userMapper.insertUser(user);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean updateUser(User user) {
        user.setUpdateTime(java.time.LocalDateTime.now());
        int result = userMapper.updateUser(user);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteUser(Integer id) {
        int result = userMapper.deleteUser(id);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean lockUser(Integer id) {
        int result = userMapper.lockUser(id);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean unlockUser(Integer id) {
        int result = userMapper.unlockUser(id);
        return result > 0;
    }

    @Override
    public LoginInfo login(User user) {
        // 1. 根据用户名查询用户
        User dbUser = userMapper.findByUsername(user.getUsername());
        if (dbUser == null) {
            return null; // 用户不存在
        }


        if (!dbUser.getPassword().equals(user.getPassword())) {
            return null; // 密码错误
        }

        // 3. 生成 JWT 令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        claims.put("role", dbUser.getRole());
        claims.put("avatar", dbUser.getAvatar());
        String token = JwtUtils.generateToken(claims);

        // 4. 返回登录信息
        return new LoginInfo(
                dbUser.getId(),
                dbUser.getUsername(),
                dbUser.getAvatar(),
                dbUser.getRole(),
                token
        );
    }

    @Override
    public boolean register(User user) {
        // 1. 校验用户名是否已存在
        User existUser = userMapper.findByUsername(user.getUsername());
        if (existUser != null) {
            return false; // 用户名已存在
        }


        // 3. 补充默认字段
        user.setStatus(1); // 默认状态
        user.setRole("user");     // 默认角色
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 其他默认值可根据需求补充（如 gender、memberLevel 等）

        // 4. 插入数据库
        int rows = userMapper.insert(user);
        return rows > 0; // 插入成功返回 true
    }
}